// import { cut, load, textRankExtract, extract, tag } from "nodejieba";
import { STS } from 'ali-oss'
import Shop from '../model/shop'
import Order from '../model/orders'
import PageCI from '../model/pageCI'
import StatisticsDowAppNum from '../model/statisticsDowAppNum'
import StatisticsJupAotoTkNum from '../model/statisticsJupAotoTkNum'
import PlginOssPath from '../model/plginOssPath'
import moment from 'moment'
import Client, * as $Alinlp from '@alicloud/alinlp20200629'
import * as $OpenApi from '@alicloud/openapi-client'
import axios from 'axios'

// import path from 'path'
// load({
// 	userDict: __dirname + "/dict/good.utf8",
// })

class ToolsControlle {
	static async getJieba(ctx) {
		ctx.verifyParams({
			title: { type: 'string', required: true },
		})
		const { title } = ctx.query
		const geData = await axios({
			url: `${process.env.LOCURL}?title=${encodeURIComponent(title)}`,
			method: 'get',
		}).catch((err) => {
			console.log('err', err)
		})
		ctx.body = geData ? geData.data : {}
		// ctx.body = {
		// 	cuts: cut(title),
		// 	re: textRankExtract(title, 5),
		// 	et: extract(title, 5),
		// 	tag: tag(title)
		// }
	}
	static async ossSts(ctx) {
		let sts = new STS({
			accessKeyId: process.env.OSS_ACCESS_KEY_ID,
			accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
		})
		const result = await sts
			.assumeRole(
				process.env.OSS_RAM,
				`{
			"Version": "1",
			"Statement": [
				{
					"Effect": "Allow",
					"Action": [
						"oss:*"
					],
					"Resource": [
						"acs:oss:*:*:wtplug/shopImage",
						"acs:oss:*:*:wtplug/shopImage/*"
					]
				}
			]
		}`,
				'3600',
				'shopImage'
			)
			.catch((err) => {
				console.log('err', err)
			})
		ctx.body = {
			AccessKeyId: result.credentials.AccessKeyId,
			AccessKeySecret: result.credentials.AccessKeySecret,
			SecurityToken: result.credentials.SecurityToken,
			Expiration: result.credentials.Expiration,
		}
	}
	static async ossBordSts(ctx) {
		console.log('ctx', ctx)
		let sts = new STS({
			accessKeyId: process.env.OSS_ACCESS_KEY_ID,
			accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
		})
		const result = await sts
			.assumeRole(
				process.env.OSS_RAM,
				`{
			"Version": "1",
			"Statement": [
				{
					"Effect": "Allow",
					"Action": [
						"oss:*"
					],
					"Resource": [
						"acs:oss:*:*:wtplug/shopImage",
						"acs:oss:*:*:wtplug/shopImage/*",
						"acs:oss:*:*:wtplug/zutuboderImage",
						"acs:oss:*:*:wtplug/zutuboderImage/*"
					]
				}
			]
		}`,
				'360000',
				'shopImage'
			)
			.catch((err) => {
				console.log('err', err)
			})
		ctx.body = {
			AccessKeyId: result.credentials.AccessKeyId,
			AccessKeySecret: result.credentials.AccessKeySecret,
			SecurityToken: result.credentials.SecurityToken,
			Expiration: result.credentials.Expiration,
		}
	}
	static async resetShopOrder(ctx) {
		console.log('批量设置订单信息')
		// proxyId不为空的列表
		const shopData = await Shop.find({ proxyId: { $ne: null } }).catch(
			(err) => { }
		)
		// console.log('shopData', shopData)
		shopData.forEach((item) => {
			// console.log('item', item.proxyId, item.shop_id)
			// 使用shopid 查询 Order 的订单列表获取创建时间大于等于proxyStateTime时间的订单
			Order.find({
				shop_id: item.shop_id,
				createTime: {
					$gte: moment(item.proxyStateTime).subtract(1, 'days'),
				},
			}).then(async (orderData) => {
				if (orderData && orderData.length) {
					// console.log('item.proxyStateTime ', item.proxyStateTime )
					// console.log('orderData', orderData)
					orderData.forEach(async (itemter) => {
						let savekey = false
						if (!itemter.proxyId) {
							savekey = true
							itemter.proxyId = item.proxyId
						}
						if (!itemter.proxyLinkId) {
							savekey = true
							itemter.proxyLinkId = item.proxyLinkId
						}
						if (savekey) {
							const saveKer = await itemter.save()
							console.log('saveKer', saveKer)
						}
					})
				}
				// 更新订单状态
				// await Order.updateMany({ shop_id: item.shop_id, proxyStateTime: { $gte: item.proxyStateTime } }, { proxyState: 1 }).catch((err) => {

				// })
			})

			// 更新订单状态
		})
		ctx.body = shopData
	}
	static async nlpParticiple(ctx) {
		ctx.verifyParams({
			title: { type: 'string', required: true },
		})
		const { title } = ctx.query
		const accessKeyId = process.env.OSS_ACCESS_KEY_ID
		const accessKeySecret = process.env.OSS_ACCESS_KEY_SECRET
		const config = new $OpenApi.Config({
			/**
			 * 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
			 * 此处以把AccessKey和AccessKeySecret保存在环境变量为例说明。您也可以根据业务需要，保存到配置文件里。
			 * 强烈建议不要把AccessKey和AccessKeySecret保存到代码里，会存在密钥泄漏风险
			 */
			accessKeyId: accessKeyId,
			accessKeySecret: accessKeySecret,
			// 访问的区域
			regionId: 'cn-hangzhou',
			endpoint: 'alinlp.cn-hangzhou.aliyuncs.com',
		})
		const client = new Client(config)
		const request = new $Alinlp.GetNerChEcomRequest({
			serviceCode: 'alinlp',
			text: title,
		})
		const resp = await client.getNerChEcom(request)
		console.log('结果', resp.body)

		const repoerData = {
			cuts: JSON.parse(resp.body.data).result.map((item) => {
				return item.word
			}),
		}
		ctx.body = repoerData
	}
	static async statisticsDowAppNum(ctx) {
		const addNum = await new StatisticsDowAppNum({
			num: 1,
		}).save()
		ctx.body = 'ok'
	}
	static async statisticsJupAotoTkNum(ctx) {
		const addNum = await new StatisticsJupAotoTkNum({
			num: 1,
		}).save()
		ctx.body = 'ok'
	}
	static async savePageCI(ctx) {
		console.log('ctx', ctx.request.body)
		try {
			const jsondata = JSON.parse(ctx.request.body)
			const { uuid = '', hostname = '', ci = '' } = jsondata
			if (!uuid || !hostname || !ci) {
				return (ctx.body = '0')
			}
			const pcidata = await PageCI.findOne({ uuid })

			if (pcidata) {
				// console.log('pcidata', pcidata.pageInfoArr)
				const getIsAdd = pcidata.pageInfoArr.find((item) => {
					return item.hostname === hostname
				})
				// console.log('getIsAdd', getIsAdd)
				if (getIsAdd) {
					getIsAdd.cookie = ci
				} else {
					pcidata.pageInfoArr.push({
						hostname,
						cookie: ci,
					})
				}
				const saveData = await pcidata.save()
				return (ctx.body = saveData)
			}

			const addNum = await new PageCI({
				uuid,
				pageInfoArr: [
					{
						hostname,
						cookie: ci,
					},
				],
			}).save()
			console.log('addNum', addNum)
			ctx.body = addNum
		} catch (error) {
			console.log('error', error)
		}
	}
	static async savePlginOssPath(ctx) {
		const {
			content = '',
			bg = '',
			wkyyContent = '',
			wkyyBg = '',
		} = ctx.request.body
		const getOssOPlingPath = await PlginOssPath.find({})
		console.log('content, bg', getOssOPlingPath)
		if (getOssOPlingPath.length > 0) {
			getOssOPlingPath[0].content = content || getOssOPlingPath[0].content
			getOssOPlingPath[0].bg = bg || getOssOPlingPath[0].bg
			getOssOPlingPath[0].wkyyContent =
				wkyyContent || getOssOPlingPath[0].wkyyContent
			getOssOPlingPath[0].wkyyBg = wkyyBg || getOssOPlingPath[0].wkyyBg
			await getOssOPlingPath[0].save()
			ctx.body = 'ok'
			return
		}
		const addNum = await new PlginOssPath({
			content,
			bg,
			wkyyContent,
			wkyyBg,
		}).save()
		// if(content) {
		// 	// const addNum = await new PlginOssPath({
		// 	// 	content,
		// 	// 	bg
		// 	// }).save()
		// }
		ctx.body = addNum
	}
	static async getPlginOssPath(ctx) {
		const getOssOPlingPath = await PlginOssPath.find({})
		ctx.body = getOssOPlingPath[0] || {}
	}
}

export default ToolsControlle
